//获取dom元素
const list = document.querySelector('.list')
const total = document.querySelector('.total')

//发请求
const getStudentData = async () => {
  const res = await axios({ url: '/students' })
  console.log(res)
  //渲染到页面
  const htmlStr = res.data
    .map((item) => {
      return `<tr>
    <td>${item.name}</td>
    <td>${item.age}</td>
    <td>${item.gender ? '男' : '女'}</td>
    <td>${item.group}</td>
    <td>${item.hope_salary}</td>
    <td>${item.salary}</td>
    <td>${item.province + item.city + item.area}</td>
    <td>
      <a href="javascript:;" class="text-success mr-3"
        ><i class="bi bi-pen" data-id='${item.id}'></i
      ></a>
      <a href="javascript:;" class="text-danger"
        ><i class="bi bi-trash" data-id='${item.id}'></i
      ></a>
    </td>
  </tr>`
    })
    .join('')
  list.innerHTML = htmlStr
  total.innerHTML = res.data.length
}
getStudentData()

// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')
// const form = document.querySelector('#form')
const submit = document.querySelector('#submit')

// modal.show()
//发起请求
const foundArea = async () => {
  //获取省份数据
  const res = await axios({ url: '/api/province' })
  // console.log(res.list)
  const provinceStr = res.data
    .map((item) => {
      return `<option value="${item}">--${item}--</option>`
    })
    .join('')
  ps.innerHTML = `<option value="">--省份--</option>${provinceStr}`
  ps.addEventListener('change', async function () {
    // console.log(ps.value)
    const res = await axios({ url: '/api/city', params: { pname: ps.value } })
    // console.log(res)
    const cityStr = res.data
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = `<option value="">--城市--</option>${cityStr}`
  })
  // console.log(res)
  // 渲染城市的下拉框
  cs.addEventListener('change', async function () {
    const res = await axios({
      url: '/api/area',
      params: { pname: ps.value, cname: cs.value },
    })
    // console.log(res)
    const areaStr = res.data
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = `<option value="">--城市--</option>${areaStr}`
  })
}
foundArea()
//获取按钮dom元素
const btn = document.querySelector('#openModal')
btn.addEventListener('click', function () {
  form.reset()
  modalBox.dataset.id = 'add'
  modalBox.querySelector('.modal-title').innerHTML = '添加学员信息'
  modal.show()
})
//给提交的按钮绑定点击事件
submit.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  //转换数据类型
  data.age = +data.age
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  data.gender = +data.gender
  data.group = +data.group
  if (data.group < 1 || data.group > 8) return alert('输入的组必须是1-8组')

  if (modalBox.dataset.id === 'add') {
    try {
      const res = await axios({
        url: '/students',
        method: 'post',
        data,
      })
      modal.hide()
      foundArea()
      alert(res.message)
    } catch (error) {
      alert(error)
    }
  } else {
    try {
      const res = await axios({
        url: '/students' + modalBox.dataset.id,
        method: 'put',
        data,
      })
      //关闭modal层
      modal.hide()
      //调用渲染函数重新刷新页面
      foundArea()

      //提示用户已经添加成功
      alert(res.message)
    } catch (error) {
      alert(error)
    }
  }
})
//事件委托
list.addEventListener('click', async function (e) {
  console.log(e)
  if (e.target.classList.contains('bi-pen')) {
    console.log('我是编辑功能')
    // console.log(e.target.dataset.id)
    //获取学生的id
    const id = e.target.dataset.id
    //发起请求
    const res = await axios({ url: '/students/' + id })
    // console.log(res.data)
    const nodelist = modalBox.querySelectorAll('[name')
    nodelist.forEach((item) => {
      if (item.name === 'gender') {
        console.log(res.data[item.name])
        res.data[item.name]
          ? (modalBox.querySelector('#cb01').checked = true)
          : (modalBox.querySelector('#cb02').checked = true)
      }
      item.value = res.data[item.name]
    })
    //获取城市列表
    const { data: citydata } = await axios({
      url: 'api/city',
      params: { pname: res.data.province },
    })
    // console.log(citydata)
    const cityStr = citydata
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = `<option value="">--城市--</option>${cityStr}`
    cs.value = res.data.city
    // 获取地区列表
    const { data: areadata } = await axios({
      url: '/api/area',
      params: { pname: res.data.province, cname: res.data.city },
    })
    const areaStr = areadata
      .map((item) => {
        return `<option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = `<option value="">--城市--</option>${areaStr}`
    as.value = res.data.area
    modalBox.dataset.id = id
    modalBox.querySelector('.modal-title').innerHTML = '修改学员信息'
    //打开modal层
    modal.show()
  }
  if (e.target.classList.contains('bi-trash')) {
    console.log('我是删除功能')
    //获取学生的id
    const id = e.target.dataset.id

    //发起删除学生请求
    await axios({ url: '/students/' + id, method: 'DELETE' })

    //调用渲染函数重新刷新页面
    foundArea()

    //提示用户已经删除成功了
    alert('删除成功')
  }
})
